package com.kj.platformlogistics.my.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.kj.platformlogistics.R;
import com.kj.platformlogistics.base.BaseActivity;
import com.kj.platformlogistics.common.MethodUtils;
import com.kj.platformlogistics.common.UserData;
import com.kj.platformlogistics.constants.UrlConstants;
import com.kj.platformlogistics.home.activity.FinishActivity;
import com.kj.platformlogistics.home.activity.SolicilationedDetailActivity;
import com.kj.platformlogistics.http.HttpRequest;
import com.kj.platformlogistics.http.HttpStringCallBack;
import com.kj.platformlogistics.login.LoginActivity;
import com.kj.platformlogistics.login.model.LoginModel;
import com.kj.platformlogistics.main.MainActivity;
import com.kj.platformlogistics.my.model.UserInfoModel;
import com.kj.platformlogistics.util.GlideEngine;
import com.kj.platformlogistics.util.JsonUtils;
import com.kj.platformlogistics.util.PictureUtils;
import com.kj.platformlogistics.util.SPUtils;
import com.kj.platformlogistics.util.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActivityPersonInfo extends BaseActivity implements View.OnClickListener {
    private TextView tvUserPhone;
    private TextView tvIdCardType;
    private TextView tvUserName;
    private TextView tvCarNumber;
    private TextView tvCarLength;
    private ImageView ivHeadLink;

    private LinearLayout llCarNumber,llCarLength,llHeadLink,llPhone;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, ActivityPersonInfo.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llHeadLink:
                //修改头像
                PictureSelector.create(ActivityPersonInfo.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .isCamera(true)
                        .compressQuality(100)
                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                        .forResult(PictureConfig.REQUEST_CAMERA);
                break;
            case R.id.llPhone:
                ActivityPhoneModify.actionStart(ActivityPersonInfo.this);
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_person_info;
    }

    @Override
    protected void initView() {
        setTitleText("个人资料");
        tvUserName=findViewById(R.id.tvUserName);
        tvUserPhone=findViewById(R.id.tvUserPhone);
        llHeadLink=findViewById(R.id.llHeadLink);
        tvIdCardType=findViewById(R.id.tvIdCardType);
        tvCarNumber=findViewById(R.id.tvCarNumber);
        llCarNumber=findViewById(R.id.llCarNumber);
        tvCarLength=findViewById(R.id.tvCarLength);
        llPhone=findViewById(R.id.llPhone);
        llCarLength=findViewById(R.id.llCarLength);
        ivHeadLink=findViewById(R.id.ivHeadLink);
        llHeadLink.setOnClickListener(this::onClick);
        llPhone.setOnClickListener(this::onClick);
    }

    @Override
    protected void initData() {

        getPersonInfo();

    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }


    private void getPersonInfo() {
        new HttpRequest(getContext()).doPost(UrlConstants.logistics_getStationUserInfo, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), UserInfoModel.class);
                        if (obj instanceof UserInfoModel) {
                            UserInfoModel model = (UserInfoModel) obj;
                            setView(model);
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void setView(UserInfoModel model){
        tvUserName.setText(model.getResult().getName());
        tvIdCardType.setText(model.getResult().getCardType()==null?"身份证":model.getResult().getCardType());
        if (model.getResult().getPhone()!=null&&model.getResult().getPhone().length()==11){
            tvUserPhone.setText(model.getResult().getPhone().substring(0,3)+"****"+model.getResult().getPhone().substring(7,11));
        }
        Glide.with(ActivityPersonInfo.this)
                .load(model.getResult().getAvatar())
                .placeholder(R.mipmap.default_headlink)
                .apply(new RequestOptions().transform(new PictureUtils()))
                .into(ivHeadLink);

        if (UserData.create(ActivityPersonInfo.this).get(UserData.ROLE).equals("0")){
            llCarNumber.setVisibility(View.VISIBLE);
            llCarLength.setVisibility(View.VISIBLE);
            tvCarNumber.setText(model.getResult().getDriverPlateNumber());
            tvCarLength.setText(model.getResult().getDriverCarLenght()+"米");
        }else {
            llCarNumber.setVisibility(View.GONE);
            llCarLength.setVisibility(View.GONE);
        }
    }

    private String path="";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.REQUEST_CAMERA:
                    // 结果回调
                    List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                    if(cameraList.size()>0){
                        path=cameraList.get(0).getRealPath();
                    }
                    uploadImg(path);
                    break;
                default:
                    break;
            }
        }
    }

    public void uploadImg(String path){
        new HttpRequest(ActivityPersonInfo.this).doUploadFile(UrlConstants.common_upload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Glide.with(ActivityPersonInfo.this).load(message)
                                .placeholder(R.mipmap.default_image)
                                .apply(new RequestOptions().transform(new PictureUtils()))
                                .into(ivHeadLink);
                        updateData(message);
                    }else {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    public void updateData(String path){
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("avatar",path);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(ActivityPersonInfo.this).doPost(UrlConstants.logistics_modifyStationUserInfo, "", jsonObject,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, "上传头像成功！", 1);
                        toastUtil.show();
                    }else {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

}
